<template>
  <div class="project-supplier-detail">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>供应商详情</span>
          <el-button @click="goBack">返回</el-button>
        </div>
      </template>

      <!-- 项目信息展示 -->
      <el-row :gutter="20" class="project-info">
        <el-col :span="24">
          <h3>项目信息</h3>
        </el-col>
        <el-col :span="12">
          <el-form label-width="120px">
            <el-form-item label="项目名称:">
              <span>{{ projectInfo.projectName || '-' }}</span>
            </el-form-item>
            <el-form-item label="项目编码:">
              <span>{{ projectInfo.projectCode || '-' }}</span>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12">
          <el-form label-width="120px">
            <el-form-item label="项目描述:">
              <span>{{ projectInfo.projectDesc || '-' }}</span>
            </el-form-item>
            <el-form-item label="创建时间:">
              <span>{{ formatDate(projectInfo.createTime) || '-' }}</span>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <el-divider />

      <!-- 供应商信息表单 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <h3>供应商信息</h3>
        </el-col>
        <el-col :span="24">
          <el-form 
            :model="supplierForm" 
            :rules="formRules"
            ref="supplierFormRef"
            label-width="120px"
            style="max-width: 800px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="供应商名称" prop="supplierName">
                  <el-input 
                    v-model="supplierForm.supplierName" 
                    readonly
                    placeholder="请选择供应商"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商编码">
                  <el-input 
                    v-model="supplierForm.supplierCode" 
                    readonly
                    placeholder="自动填充"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="供应商类型">
                  <el-input 
                    v-model="supplierForm.supplierType" 
                    readonly
                    placeholder="自动填充"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同金额" prop="amount">
                  <el-input-number
                    v-model="supplierForm.amount"
                    :precision="2"
                    :min="0"
                    placeholder="请输入合同金额"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="币种" prop="currency">
                  <el-select 
                    v-model="supplierForm.currency" 
                    placeholder="请选择币种"
                    style="width: 100%"
                  >
                    <el-option label="人民币" value="人民币" />
                    <el-option label="美元" value="美元" />
                    <el-option label="欧元" value="欧元" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同签订日期" prop="contractDate">
                  <el-date-picker
                    v-model="supplierForm.contractDate"
                    type="date"
                    placeholder="请选择合同签订日期"
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系人">
                  <el-input 
                    v-model="supplierForm.contactPerson" 
                    readonly
                    placeholder="自动填充"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电话">
                  <el-input 
                    v-model="supplierForm.phone" 
                    readonly
                    placeholder="自动填充"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱">
                  <el-input 
                    v-model="supplierForm.email" 
                    readonly
                    placeholder="自动填充"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同编号">
                  <el-input 
                    v-model="supplierForm.contractNo" 
                    placeholder="请输入合同编号"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <div class="button-group">
        <el-button 
          type="primary" 
          @click="handleSelectSupplier"
          :disabled="!projectInfo.id"
        >
          选取供应商
        </el-button>
        <el-button 
          type="success" 
          @click="handleSave"
          :loading="saving"
          :disabled="!supplierForm.supplierId"
        >
          保存
        </el-button>
        <el-button @click="goBack">取消</el-button>
      </div>
    </el-card>

    <!-- 供应商选择对话框 -->
    <SupplierSelect
      v-model:visible="supplierSelectVisible"
      @confirm="handleSupplierSelected"
    />
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { projectService } from '../services/supplierService.js';
import SupplierSelect from './SupplierSelect.vue';

export default {
  name: 'ProjectSupplierDetail',
  components: {
    SupplierSelect
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    
    // 响应式数据
    const loading = ref(false);
    const saving = ref(false);
    const supplierSelectVisible = ref(false);
    const supplierFormRef = ref(null);
    
    // 项目信息
    const projectInfo = reactive({
      id: null,
      projectName: '',
      projectCode: '',
      projectDesc: '',
      createTime: null
    });
    
    // 供应商表单
    const supplierForm = reactive({
      supplierId: null,
      supplierName: '',
      supplierCode: '',
      supplierType: '',
      contactPerson: '',
      phone: '',
      email: '',
      amount: null,
      currency: '人民币',
      contractDate: '',
      contractNo: ''
    });

    // 表单验证规则
    const formRules = {
      supplierName: [
        { required: true, message: '请选择供应商', trigger: 'blur' }
      ],
      amount: [
        { required: true, message: '请输入合同金额', trigger: 'blur' }
      ],
      currency: [
        { required: true, message: '请选择币种', trigger: 'change' }
      ],
      contractDate: [
        { required: true, message: '请选择合同签订日期', trigger: 'change' }
      ]
    };

    // 获取项目详情
    const getProjectDetail = async () => {
      try {
        loading.value = true;
        const projectId = route.params.id;
        
        if (!projectId) {
          ElMessage.error('项目ID不能为空');
          return;
        }

        const response = await projectService.getProjectDetail(projectId);
        
        if (response.code === 200) {
          const data = response.data;
          
          // 填充项目信息
          Object.assign(projectInfo, {
            id: data.id,
            projectName: data.projectName,
            projectCode: data.projectCode,
            projectDesc: data.projectDesc,
            createTime: data.createTime
          });

          // 如果已关联供应商，填充供应商信息
          if (data.supplier) {
            Object.assign(supplierForm, {
              supplierId: data.supplier.id,
              supplierName: data.supplier.supplierName,
              supplierCode: data.supplier.supplierCode,
              supplierType: data.supplier.supplierType,
              contactPerson: data.supplier.contactPerson,
              phone: data.supplier.phone,
              email: data.supplier.email,
              amount: data.supplier.amount,
              currency: data.supplier.currency,
              contractDate: data.supplier.contractDate,
              contractNo: data.supplier.contractNo
            });
          }
        } else {
          ElMessage.error(response.message || '获取项目详情失败');
        }
      } catch (error) {
        console.error('获取项目详情失败:', error);
        ElMessage.error('获取项目详情失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    };

    // 选择供应商
    const handleSelectSupplier = () => {
      supplierSelectVisible.value = true;
    };

    // 供应商选择确认
    const handleSupplierSelected = (supplier) => {
      Object.assign(supplierForm, {
        supplierId: supplier.id,
        supplierName: supplier.supplierName,
        supplierCode: supplier.supplierCode,
        supplierType: supplier.supplierType,
        contactPerson: supplier.contactPerson,
        phone: supplier.phone,
        email: supplier.email
      });
      
      supplierSelectVisible.value = false;
      ElMessage.success('供应商选择成功');
    };

    // 保存项目供应商关联
    const handleSave = async () => {
      try {
        // 表单验证
        const valid = await supplierFormRef.value.validate();
        if (!valid) return;

        saving.value = true;
        
        const saveData = {
          projectId: projectInfo.id,
          supplierId: supplierForm.supplierId,
          contractDate: supplierForm.contractDate,
          amount: supplierForm.amount,
          currency: supplierForm.currency,
          contractNo: supplierForm.contractNo
        };

        const response = await projectService.saveProjectSupplier(saveData);
        
        if (response.code === 200) {
          ElMessage.success('保存成功');
          // 保存成功后返回列表页
          setTimeout(() => {
            goBack();
          }, 1000);
        } else {
          ElMessage.error(response.message || '保存失败');
        }
      } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败，请稍后重试');
      } finally {
        saving.value = false;
      }
    };

    // 返回上一页
    const goBack = () => {
      router.push({ name: 'SupplierProjectList' });
    };

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '';
      const d = new Date(date);
      return d.toLocaleDateString('zh-CN');
    };

    // 组件挂载时获取数据
    onMounted(() => {
      getProjectDetail();
    });

    return {
      loading,
      saving,
      supplierSelectVisible,
      supplierFormRef,
      projectInfo,
      supplierForm,
      formRules,
      getProjectDetail,
      handleSelectSupplier,
      handleSupplierSelected,
      handleSave,
      goBack,
      formatDate
    };
  }
};
</script>

<style scoped>
.project-supplier-detail {
  padding: 20px;
}

.detail-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.project-info {
  margin-bottom: 20px;
}

.project-info h3 {
  margin-bottom: 20px;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.project-info .el-form-item {
  margin-bottom: 15px;
}

.project-info .el-form-item__label {
  font-weight: bold;
}

.button-group {
  margin-top: 30px;
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.button-group .el-button {
  margin: 0 10px;
  padding: 12px 30px;
}

h3 {
  margin-bottom: 20px;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-divider {
  margin: 30px 0;
}
</style> 